package controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.PutCache;
import server.UpdateDomain;

import models.Domain;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class WhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        if(count != 2)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return;
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		title_url = Utils.fomatDomain(title_url);
		if(title_url!=null&&Utils.checkDomain(title_url))
		{
			try {
				ObjectifyService.register(Domain.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
//				
				Domain domain = objectify.get(new Key<Domain>(Domain.class, title_url));
				
				PutCache.putCacheList(domain.getDomain(), "view",18);
				
				if(domain.getStatus()==10)
				{
					resp.sendError(resp.SC_NOT_FOUND,"Content removed because our policy !");
				}
				
				req.setAttribute("domain", domain);
			} catch (Exception e) {
				Domain domain = new Domain();
				domain.setDomain(title_url);
				new UpdateDomain(domain);
				resp.sendRedirect("/w/"+title_url);
				return;
			}
			
			try {
				req.getRequestDispatcher("/whois.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			resp.sendRedirect("/gsearch?cx=012442764171928889326:_zsyjyuyyuu&cof=FORID%3A10&ie=UTF-8&q="+title_url+"&sa=Search");
		}
	}
}
